package com.github.baichuan.iot.gateway.context;

import io.netty.channel.Channel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.lang.ref.WeakReference;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 设备上下文信息
 */
@Getter
@Setter
@Slf4j
@ToString
public class DeviceContext {
    /**
     * 设备标识
     */
    private String device;

    /**
     * 开启调试
     */
    private boolean debug;

//    /**
//     * 数据出口
//     */
//    private String pipeline;

    private WeakReference<Channel> channel;
    /**
     * 设备地址
     */
    private SocketAddress recipient;

    /**
     * 下发消息流水号
     */
    private AtomicInteger sequence = new AtomicInteger();


    private Map<String, Object> attributes = new HashMap<>();

//    /**
//     * 最后上行信息
//     */
//    private DatagramContext lastInbound;

    /**
     * 关闭当前会话
     */
    public void close(){
        if(channel.get() != null && channel.get().isOpen()){
            channel.get().close();
        }
    }

    /**
     * 获取出站消息流水号
     * @return
     */
    public int outboundSequence(){
        return sequence.getAndIncrement();
    }

    public void putAttribute(String key, Object value){
        attributes.put(key, value);
    }

    public <T> Optional<T> getAttribute(@NonNull String name, @NonNull Class<T> clazz){
        if(attributes.containsKey(name))
            return Optional.of(clazz.cast(attributes.get(name)));
        else
            return Optional.empty();
    }
}
